package com.ding.easycontroller.utils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class FileUtils {


    public static void copyStream(InputStream in,OutputStream out) throws IOException{
        byte[] buf = new byte[1024];
        int len;

        //添加一个实体
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }

    }

    //读取文件
    public static void zipInputStreamToFiles(InputStream inputStream,File target)throws IOException{
        if (!target.exists()){

            //创建路径
            target.mkdirs();
        }

        if (!target.isDirectory()){
            throw new RuntimeException("输出必须是一个路径");
        }

        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        ZipEntry entry =null;

        while ((entry=zipInputStream.getNextEntry())!=null){
            String name = entry.getName();
            File file = new File(target,name);
            file.createNewFile();
            FileOutputStream outputStream = new FileOutputStream(file);
            copyStream(zipInputStream,outputStream);
            zipInputStream.closeEntry();
            outputStream.close();
        }

    }

    //将输入流整合输出到同一个zip输出流

    public static void inputToZipOutput(Map<String, InputStream> inputStreams, ZipOutputStream zos) throws IOException{

        for (String name : inputStreams.keySet()) {
            InputStream in = inputStreams.get(name);
            zos.putNextEntry(new ZipEntry(name));
            copyStream(in,zos);
            //关闭实体
            zos.closeEntry();
        }

    }

    //将多个文件输出到同一个输出流中
    public static void filesToZipOutputStream(List<File> srcFiles, OutputStream out) throws IOException {

        //遍历所有的文件
        Map<String,InputStream> inputStreamMap=new HashMap<>();

        for (File file : srcFiles) {
            InputStream in =new FileInputStream(file);
            inputStreamMap.put(file.getName(),in);
        }

        inputToZipOutput(inputStreamMap,new ZipOutputStream(out));

        //关流操作
        for (InputStream value : inputStreamMap.values()) {
            value.close();
        }

    }

    public static void filesToZipFile(List<File> files,File target) throws IOException{

        OutputStream outputStream=new FileOutputStream(target);

        filesToZipOutputStream(files,outputStream);

        outputStream.close();
    }

    public static void copyFile(File source, File target) throws IOException{
        FileInputStream inputStream = new FileInputStream(source);
        FileOutputStream fileOutputStream = new FileOutputStream(target);
        copyStream(inputStream, fileOutputStream);
        inputStream.close();
        fileOutputStream.close();
    }

}
